package com.jse.io.nio.network.old.muti;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.jse.network.StreamUtil;

/**
 * http://tutorials.jenkov.com/java-networking/server-sockets.html
 * 
 * @author zenghua233
 *
 */
public class OneServer {
	public static void main(String[] args) throws Exception {
		OneServer oneServer = new OneServer();
		oneServer.createServer();
	}
	
	/**
	 * http://javaman.group.iteye.com/group/wiki/3404-cuisuqiang-google-socket-InputStream-OutputStream
	 * @throws Exception
	 */
	public void createServer() throws Exception {
		ServerSocket server = new ServerSocket(88);
		
//		SocketAddress address = new InetSocketAddress(InetAddress.getLocalHost(), 99);
//		server.bind(address);
		
		while (true) {
			System.out.println("执行几次");
			ExecutorService executor = Executors.newFixedThreadPool(10);
			//accept是阻塞的，直到建立连接，客户端是多个线程执行，当第二个线程过来，这里就开始阻塞了
			Socket socket = server.accept();
			ServerWorker worker = new ServerWorker("", socket);
			executor.execute(worker);
		}
			
//			new Thread(new ServerWorker("", socket)).start();
	}
	
	class ServerWorker implements Runnable {
		private String name;
		private Socket socket;
		
		private ServerWorker(String name, Socket socket) {
			this.name = name;
			this.socket = socket;
		}
		
		@Override
		public void run() {
			InputStream input = null;
			try {
				input = socket.getInputStream();
				
				System.out.println("线程-" + Thread.currentThread().getName() + "-启动");
				
//				while (true) {
//					System.out.println("server: " + StreamUtil.getInput(input));
//				}
					
				PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
				writer.println("server: acked!");
				
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
//					input.close();
//					socket.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		}
	}
}
